//
//  OALoginViewController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/20.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "webtViewController.h"
#import "anquanwebViewController.h"
#import "SDKWrapper.h"
#import "xxx.h"
#import <CoreTelephony/CTCarrier.h>  
#import "OALoginViewController.h"
#import "MainViewController.h"
#import "XmlParseHelper.h"
//#import "AuthHelper.h"
//#import "sdkheader.h"
//#import "sslvpnnb.h"
#import "webViewController.h"
#import "MainTabBarController.h"
#import "MenuViewController.h"
#import "ZLCGuidePageView.h"

@interface OALoginViewController ()<UITextFieldDelegate>
{
    int firstLoginType;

}
@property(nonatomic,strong)NSArray * array;
@property(nonatomic,strong)NSDictionary * dic2;

@end

@implementation OALoginViewController
short port = 443;                        //vpn设备端口号，一般为443
//NSString *vpnIp =    vpnid;  //vpn设备IP地址
NSString *userName = @"testfz";             //用户名认证的用户名
NSString *password = @"123456";                //用户名认证的密码

NSString *certName = @"";     //导入证书名字，如果服务端没有设置证书认证可以不设置
NSString *certPwd =  @"";          //证书密码，如果服务端没有设置证书
// 360
NSString* const kVPN_HOST              = @"122.225.70.186";
NSString* const kVPN_PORT              = @"443";
NSString* const kLOGIN_USERNAME        = @"jxgqadmin";
NSString* const kLOGIN_PASSSWORD       = @"password";
NSString* const kVPN_AUTH_NAME         = @"本地认证";

//NSString* const kVPN_HOST               = @"vpn网关的地址";
//NSString* const kVPN_PORT               = @"vpn网关的端口（默认是443）";
//
////用户名密码登录配置
//NSString* const kLOGIN_USERNAME        = @"vpn登录用户名";
//NSString* const kLOGIN_PASSSWORD       = @"vpn登录的密码";
//NSString* const kVPN_AUTH_NAME         = @"认证服务器（一般是本地认证）";
FOUNDATION_EXTERN NSString *const SPSDKSSLVPNTopicNotification;

typedef NS_ENUM(NSInteger, SPNCStatus) {
    /* 断开连接 */
    SPNCStatusDisconnected = 1,
    /* 正在连接中 */
    SPNCStatusConnecting = 2,
    /* 已经连接 */
    SPNCStatusConnected = 3,
};
-(void)onSSLVPNSessionNotify:(NSNotification*)noti
{
    NSDictionary* dic = [noti object];
    NSLog(@"demo topic dic = %@", dic);
}
- (void)viewWillAppear:(BOOL)animated{
   

}
- (void)viewDidLoad {


    [super viewDidLoad];
    
    _ipbutton.hidden = YES;

//    if([[NSUserDefaults standardUserDefaults]boolForKey:@"firstStart"]){

 if(![[NSUserDefaults standardUserDefaults]boolForKey:@"firstip"]){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstip"];
//引导页图片数组
 [[NSUserDefaults standardUserDefaults] setObject:@"112.11.119.146" forKey:@"vpnid"];
}
 if(![[NSUserDefaults standardUserDefaults]boolForKey:@"firstsave"]){

_bgview0= [[UIView alloc]initWithFrame:CGRectMake(0, 0,KScreenWidth, KScreenHeight)];
_bgview0.backgroundColor = [UIColor colorWithWhite:.3 alpha:.7];
//_bgview0.alpha = 0.7;
[self.view addSubview:_bgview0];

_bgview = [[UIView alloc]initWithFrame:CGRectMake(20, 200,KScreenWidth-40, 150)];
_bgview.backgroundColor = [UIColor whiteColor];
_bgview.alpha = 1;

[_bgview0 addSubview:_bgview];
UILabel *label = [[UILabel alloc]init];
label.numberOfLines = 0;
label.frame = CGRectMake(5, 5, _bgview.width-10, 120);
label.text = @"嘉兴港区移动用户应重视并遵守网络信息安全等相关法律法规，承担相应信息安全责任。在使用协同办公（移动版）前，请查阅《信息安全须知》";
[_bgview addSubview:label];
UIColor *bgcolor = self.view.tintColor;
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitleColor:bgcolor forState:UIControlStateNormal];
[button setTitle:@"查看详情" forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize: 13.0];

button.frame = CGRectMake(_bgview.width-110, label.bottom,100, 20);
[button addTarget:self action:@selector(pushaction) forControlEvents:UIControlEventTouchUpInside];
[_bgview addSubview:button];
}
//}
 if(![[NSUserDefaults standardUserDefaults]boolForKey:@"firstStart"]){
//引导页图片数组

    NSArray *images =  @[[UIImage imageNamed:@"2、启动页-2（750x1334）.jpg"],[UIImage imageNamed:@"2、启动页-3（750x1334）.jpg"],[UIImage imageNamed:@"2、启动页-1（750x1334）.jpg"]];
    //创建引导页视图
    ZLCGuidePageView *pageView = [[ZLCGuidePageView alloc]initWithFrame:self.view.frame WithImages:images];
    [self.view addSubview:pageView];

}
_rememberlabel.hidden = YES;
_rememberbutton.hidden = YES;
_autlabel.hidden = YES;
_autobutton.hidden = YES;
    self.rememberbutton.selected = YES;
        // Do any additional setup after loading the view.


// 登陆按钮
[_buttonlayer.layer setMasksToBounds:YES];

[_buttonlayer.layer setCornerRadius:20.0];//设置矩形四个圆角半径

//[_buttonlayer.layer setBorderWidth:2.0];//边框宽度
UIColor *textColor = self.view.tintColor;

UIColor *color = [[UIColor blueColor]colorWithAlphaComponent:.7];
_buttonlayer.layer.borderColor=textColor.CGColor;

    UIImageView *image1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"密码_icon"]];
      image1.frame = CGRectMake(10, 5, 20, 20);
    
//image1.transform = CGAffineTransformMakeTranslation(30, 0);
       //image1.contentMode = UIViewContentModeTopLeft;
   UIView *view1 = [[UIView alloc]init];
   view1.backgroundColor = [UIColor whiteColor];
   view1.size = CGSizeMake(30,30);
   [view1 addSubview:image1];
    self.passwordTextField.leftView = view1;
    self.passwordTextField.leftViewMode = UITextFieldViewModeAlways;
UIImageView *image2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"账号_icon"]];
 image2.frame = CGRectMake(10, 5, 20, 20);
  UIView *view2 = [[UIView alloc]init];
   view2.backgroundColor = [UIColor whiteColor];
   view2.size = CGSizeMake(30,30);
   [view2 addSubview:image2];

 
    self.accountTextField.leftView = view2;
    self.accountTextField.leftViewMode = UITextFieldViewModeAlways;

 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] length] !=0) {
        self.accountTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    }
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"pwdId"] length] !=0) {
        self.passwordTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"pwdId"];
    }
//
//    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"autoLogin"] isEqualToString:@"Y"]) {
//        self.autobutton.selected = YES;
//    }
     // 判断版本
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
 CFShow((__bridge CFTypeRef)(infoDictionary));
// app名称
 NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
 // app版本
_verson= [infoDictionary objectForKey:@"CFBundleShortVersionString"];
[self _shadow];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onSSLVPNSessionNotify:)
                                                     name:SPSDKSSLVPNTopicNotification
                                                   object:nil];
}




- (void)_shadow{
 _accountTextField.layer.shadowOffset =  CGSizeMake(5,5);
    _accountTextField.layer.shadowOpacity = 0.75;
    _accountTextField.layer.shadowColor = [UIColor colorWithHexString:@"0436be" ].CGColor;
_accountTextField.layer.shadowRadius = 5;


}



- (void)pushaction{
anquanwebViewController *vc = [[anquanwebViewController alloc]init];
        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:vc];

        vc.navigationController.navigationBar.hidden = NO;
vc.navigationController.navigationBar.barStyle = UIStatusBarStyleDefault;
[vc setNeedsStatusBarAppearanceUpdate];
               self.view.window.rootViewController = navVC;

}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [self.accountTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setin{
[self.accountTextField resignFirstResponder];
[self.passwordTextField resignFirstResponder];
     NSString *strUrl = [self.accountTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
         strUrl = [strUrl lowercaseString];

    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:strUrl forKey:@"userId"];
     [params setObject:self.passwordTextField.text forKey:@"pwdId"];
//                 [defaults setObject:dt forKey:@"deviceToken"];
       NSString *dt = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceToken"];

//[HttpTools postWithURL:KLoginURL arrays:@[@{@"userId":strUrl},@{@"pwdId":self.passwordTextField.text},@{@"device":@"11"},@{@"phonetype":@"1"}] method:@"validationUser" success:^(id JSON) {
[HttpTools postWithURL:KLoginURL arrays:@[@{@"userId":strUrl},@{@"pwdId":self.passwordTextField.text},@{@"device":dt}] method:@"validationUser" success:^(id JSON) {

       [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        XmlParseHelper * parse = [[XmlParseHelper alloc]initWithData:JSON];
        NSArray * dataArray = [parse selectNodes:@"errmsg"];
        NSString * resultTag = nil;
        if (dataArray.count) {
            NSDictionary * dic  = [dataArray lastObject];
            resultTag = dic[@"text"];
        }
//         MainViewController * mainVC = [self.storyboard instantiateViewControllerWithIdentifier:@"MainVC"];
//        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:mainVC];
    
//     MainTabBarController *tar = [[MainTabBarController alloc]init];
         MenuViewController *tar = [[MenuViewController alloc]init];

    
    
        switch ([resultTag integerValue]) {
            case 1:
                 [self.view makeToast:@"您的用户名不存在，请确认后再输"];
                break;
                case 2:

               self.view.window.rootViewController = tar;
                                   [[NSUserDefaults standardUserDefaults] setObject:strUrl forKey:@"userId"];
                    [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:@"pwdId"];

//                if (self.rememberbutton.selected) {
//                    [[NSUserDefaults standardUserDefaults] setObject:strUrl forKey:@"userId"];
//                    [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:@"pwdId"];
//
//                }else{
//                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"userId"];
//                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"pwdId"];
//                }
//
//                if (!self.autobutton.selected) {
//                    [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"autoLogin"];
//                }else{
//                    [[NSUserDefaults standardUserDefaults] setObject:@"Y" forKey:@"autoLogin"];
//                }

                break;
                case 3:
                [self.view makeToast:@"您的密码错误，请确认后再输"];
                break;
                case -1099:
                [self.view makeToast:@"抱歉，服务器出错"];
                break;
            default:
                break;
        }
        
    } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
}
- (IBAction)LoginAction:(id)sender {
//if ([_type isEqualToString:@"1"]) {
//    [self setin ];
//}
//else{
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

if (self.accountTextField.text.length == 0) {
        [self.view makeToast:@"请输入账号"];
        return;
    } 
    if (self.passwordTextField.text.length == 0) {
        [self.view makeToast:@"请输入密码"];
        return;
    }
else{
 MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.labelText = @"正在登录,请稍等";
  if([[SDKWrapper getInstance] isConnected]){
                    [self setin];

  }else{
        [self vpnLogin];

}
//
////     if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"shouquanid"] length] !=0) {
////           _shouquanid = [[NSUserDefaults standardUserDefaults] objectForKey:@"shouquanid"];
// MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//                hud.labelText = @"正在登录,请稍等";
//  //调用sdk
////             [self setin];
//
//      [self vpnLogin];
////    }else{
////UIAlertView *alertView1 = [[UIAlertView alloc] initWithTitle:@"授权码" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
////    alertView1.delegate = self;
////    alertView1.alertViewStyle = UIAlertViewStylePlainTextInput;
////    UITextField * textField = [alertView1 textFieldAtIndex:0];
////    textField.placeholder = @"请输入授权码";
////    [alertView1 show];
////
////    }
//}
////    }
//// self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];
////    [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];
//
//
////}
}

}
#pragma mark vpn methods

- (void)vpnLogin
{
    //1.用户密码登录，
    //注：需要指定 kVPN_HOST， kVPN_PORT， kVPN_AUTH_NAME， kLOGIN_USERNAME， kLOGIN_PASSSWORD这些值
    //注：@"extra_ 开头的是用户自己定义的参数,extra_test_param1 只是供参考的例子
    
    //local auth , use username and password login
    
    NSDictionary *loginDic = @{@"vpn_host"      : kVPN_HOST,
                               @"vpn_port"      : kVPN_PORT,
                               @"auth_server"   : kVPN_AUTH_NAME,
                               @"auth_username" : kLOGIN_USERNAME,
                               @"auth_password" : kLOGIN_PASSSWORD,
                               @"auth_mode"     : @0,
                               @"auth_autologin": @1,
                               @"extra_test_param1" : @"extra_test_param1",
                               };
    
    
    //2.证书登录，证书是从vpn网关申请的
    //cer auth, use cer and cer password login
//    NSDictionary *loginDic = @{@"vpn_host"          : kVPN_HOST,
//                               @"vpn_port"          : kVPN_PORT,
//                               @"auth_server"       : kVPN_AUTH_NAME,
//                               @"cert"              : kLOGIN_CER,
//                               @"cert_pass"         : kLOGIN_CERPASSSWORD,
//                               @"auth_mode"         : @1,
//                               @"auth_autologin"    : @1,
//                               };
    
    //3.动态口令登录
//    NSDictionary *loginDic = @{@"vpn_host"          : kVPN_HOST,
//                               @"vpn_port"          : kVPN_PORT,
//                               @"auth_server"       : kVPN_AUTH_NAME,
//                               @"totp"              : @"动态口令",
//                               @"auth_mode"         : @2,
//                               @"auth_autologin"    : @1,
//                               };
    
    SDKWrapper* sdkWrapper = [SDKWrapper getInstance];
    [sdkWrapper runWithParams:loginDic responseHandler:^(BOOL result) {
        if(result)
        {
[self setin];
//             webtViewController *webvc = [[webtViewController alloc]init];
//             webvc.url = @"http://192.168.1.224:8081/IOSOA/";
//                 self.view.window.rootViewController = webvc;

        }
        else
        {
            NSLog(@"Login Fail");
           
        }
    }];
}

- (void)vpnLogout
{
    [[SDKWrapper getInstance] stop];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
 UITextField * textField = [alertView textFieldAtIndex:0];
        if (textField.text.length == 0) {
          [self.view makeToast:@"请输入授权码"];
          return;
        }
        _shouquanid = textField.text;
         MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.labelText = @"正在登录,请稍等";
         //调用sdk


}

//             if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"shouquanid"] length] !=0) {
//             }else{
//
//                        [self.view makeToast:@"授权码有误"];
//
//            UIAlertView *alertView1 = [[UIAlertView alloc] initWithTitle:@"授权码" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//    alertView1.delegate = self;
//    alertView1.alertViewStyle = UIAlertViewStylePlainTextInput;
//    UITextField * textField = [alertView1 textFieldAtIndex:0];
//    textField.placeholder = @"请输入授权码";
//    [alertView1 show];
//    }

//   [[NSUserDefaults standardUserDefaults] setObject:_shouquanid forKey:@"shouquanid"];

- (IBAction)IPaction:(id)sender {
 UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"网络设置" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    //可以给alertview中添加一个输入框
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"例如:192.168.0.1";
    }];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"还原" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        NSLog(@"点击了按钮1，进入按钮1的事件");
        //textFields是一个数组，获取所输入的字符串
         [[NSUserDefaults standardUserDefaults] setObject:@"112.11.119.146" forKey:@"vpnid"];

        NSLog(@"%@",alert.textFields.lastObject.text);
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"保存修改" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"%@",alert.textFields.lastObject.text);

             [[NSUserDefaults standardUserDefaults] setObject:alert.textFields.lastObject.text forKey:@"vpnid"];

        NSLog(@"点击了取消");
    }];
    
    [alert addAction:action2];
        [alert addAction:action1];

    [self presentViewController:alert animated:YES completion:nil];



}

- (IBAction)rememberbutton:(id)sender {
 self.rememberbutton.selected = !self.rememberbutton.selected;
    if (!self.rememberbutton.selected) {
        self.autobutton.selected = self.rememberbutton.selected;
    }
    

}

- (IBAction)autonbutton:(id)sender {
    self.autobutton.selected = !self.autobutton.selected;


//在此实现不打勾时的方法
}
@end
